<?php

namespace app\merchants\services;

use app\common\loader\ModelMerchant;
use Exception;
use think\db\exception\DbException;
use yiqiniu\extend\facade\Arrays;

/**
 * 分类信息
 */
class ProductClassService
{

    /**
     * 分类列表
     * @param  $where |搜索条件
     * @param  $list
     * @return array|null
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function class_list($where, $list)
    {

        return ModelMerchant::ProductClass()->classList($where, $list);
    }

    /**
     * 分类：增加，修改
     * @param $data
     * @param int $id
     * @return int
     * @throws DbException
     */
    public function save($data, int $id = 0): int
    {
        return ModelMerchant::ProductClass()->save($data, $id);
    }


    /**
     * 删除
     * @param int $id
     * @return bool
     * @throws DbException|Exception
     */
    public function del(int $id, $mer_id): bool
    {
        return ModelMerchant::ProductClass()->del($id, $mer_id);
    }

    /**
     * 详情
     * @param int $id
     */
    public function info(int $id)
    {
        return ModelMerchant::ProductClass()->info($id);
    }

    /**
     * 修改排序
     * @param int $id
     * @param int $sort
     * @return int|string
     * @throws DbException
     */
    public function save_sort(int $id, int $sort)
    {
        return ModelMerchant::ProductClass()->where('id', $id)
            ->update(null, ['sort' => $sort]);
    }


    public function getList(array $option, int $tree = 1)
    {
        $list = ModelMerchant::ProductClass()->where($option['where'])
            ->field('id,pid,title,sort,child')->order('id desc')
            ->select();

        if ($tree) {
            return Arrays::toTree($list, 'id', 'pid');
        }
        return $list;
    }
}
